﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PH.Model.Temps;
using PH.Model;
namespace PH.Data.Temps
{
    public class TBookCommand
    {
        public static void CreateNew(TBookModel model)
        {
            if (model != null)
            {
                using (DBCentre db = new DBCentre())
                {
                    model.CreatedOn = DateTime.Now;
                    model.BookNo = Utils.Password.MakeRandomPassword("NUMBER", 6);
                    var d = Convertor.ConvertFrom<TBook, TBookModel>(model);
                    db.DataContext.TBooks.Add(d);
                    db.DataContext.SaveChanges();
                }
            }
        }

        public static TBookCollection Gets(QueryBase sea)
        {
            var ret = new TBookCollection();
            using (DBCentre db = new DBCentre())
            {
                var n = 0;
                IQueryable<TBook> q = db.DataContext.TBooks;
                q = q.OrderByDescending(p => p.ID);
                if (sea != null)
                {
                    if (sea.PageSize > 0)
                    {
                        n = q.Count();
                        q = q.Skip(sea.PageSize * sea.PageIndex).Take(sea.PageSize);
                    }

                    var lst = q.ToList();
                    ret = Convertor.ConvertCollection<TBookModel, TBook, TBookCollection>(lst);
                    ret.TotalRecordsCount = n == 0 ? lst.Count : n;
                }
            }
            return ret;
        }
    }
}
